#include "common.h"

#define NAME(key) \
  [_KEY_##key] = #key,

static const char *keyname[256] __attribute__((used)) = {
  [_KEY_NONE] = "NONE",
  _KEYS(NAME)
};

int current_game = 0;

void toggle_game() {
  current_game = 1 - current_game; // 在 0 和 1 之间切换
}

size_t events_read(void *buf, size_t len) {
  unsigned long current_time = _uptime();
  // 1. 优先处理按键事件
  int key_code = _read_key();
  // 检查是否按下 F12
  if (key_code == _KEY_F12) {
    // 切换游戏逻辑
    toggle_game();
    sprintf(buf, "kd F12\n"); // 输出 F12 按下事件
  } 
  // 2. 其次处理时间事件
  if (key_code == _KEY_NONE) {
    sprintf(buf, "t %d\n", current_time);
  }
  else{
    int is_keydown = key_code & 0x8000 ? 1 : 0;
    key_code &= ~0x8000;
    sprintf(buf, "%s %s\n", is_keydown ? "kd" : "ku", keyname[key_code]);
  }
  return strlen(buf);
}

static char dispinfo[128] __attribute__((used));

void dispinfo_read(void *buf, off_t offset, size_t len) {
  strncpy(buf, dispinfo + offset, len);
}

void fb_write(const void *buf, off_t offset, size_t len) {
  // 将字节偏移转换为像素偏移（每个像素占4字节）
  uint32_t *pixels = (uint32_t *)buf;
  size_t total_pixels = len / sizeof(uint32_t);
  size_t start_pos = offset / sizeof(uint32_t);

  // 计算起始坐标 (x, y)
  int x = start_pos % _screen.width;
  int y = start_pos / _screen.width;

  while (total_pixels > 0) {
    // 计算当前行可写入的最大像素数
    int w = _screen.width - x;
    if (w > total_pixels) w = total_pixels;

    // 调用绘图函数写入一行数据
    _draw_rect(pixels, x, y, w, 1);

    // 更新指针和剩余像素数
    pixels += w;
    total_pixels -= w;

    // 移动到下一行起始位置
    x = 0;
    y++;
  }
}

void init_device() {
  _ioe_init();
  // TODO: print the string to array `dispinfo` with the format
  // described in the Navy-apps convention
  strcpy(dispinfo, "WIDTH:400\nHEIGHT:300");
}
